package com.xiyu.service.service.unit;

import com.xiyu.service.vo.unit.rank.RankSimpleListOutput;
import com.xiyu.service.vo.unit.rank.RankSingleGetOutput;
import com.xiyu.service.vo.unit.rank.RankUpdateInput;
import com.xiyu.service.vo.unit.rank.RankCreateInput;
import com.xiyu.service.model.unit.rank.UnitRank;
import com.xiyu.service.repository.unit.rank.UnitRankRepository;
import com.xiyu.service.vo.unit.rank.RankPageQueryOutput;
import com.xiyu.service.vo.unit.rank.RankPageQueryInput;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.babyfish.jimmer.Page;
import java.util.*;

import org.springframework.transaction.annotation.Transactional;
import com.xiyu.service.util.entity.EntityUtils;
import com.xiyu.service.framework.web.web.core.pojo.PageResult;
import com.xiyu.service.convert.unit.RankConvert;

import static com.xiyu.service.framework.exception.util.ServiceExceptionUtil.exception;
import static com.xiyu.service.errorCode.unit.RankErrorCode.*;

/**
 * 职级管理 Service 实现类
 */
@Service
@Validated
public class RankServiceImpl implements RankService {

    @Resource
    private UnitRankRepository unitRankRepository;




    @Override
    public PageResult<RankPageQueryOutput> pageQuery(RankPageQueryInput inputVO) {
        Page<UnitRank> pageUnitRank = unitRankRepository.pageQuery(inputVO);
        List<RankPageQueryOutput> listUnitRank = RankConvert.INSTANCE.pageQueryOutputConvert(pageUnitRank.getRows());
        return new PageResult<>(listUnitRank, pageUnitRank.getTotalRowCount());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(RankCreateInput inputVO) {
        UnitRank newUnitRank = RankConvert.INSTANCE.createInputConvert(inputVO);
        newUnitRank = unitRankRepository.insert(newUnitRank);
        return newUnitRank.id();

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(RankUpdateInput inputVO) {
        Optional<UnitRank> optionalOldUnitRank = unitRankRepository.findById(inputVO.getId());
        if(!optionalOldUnitRank.isPresent()){
            throw exception(UNIT_RANK_NOT_EXIST);
        }
        UnitRank updateUnitRank = RankConvert.INSTANCE.updateInputConvert(inputVO);
        if (!EntityUtils.isEquals(optionalOldUnitRank.get(), updateUnitRank))
            unitRankRepository.update(updateUnitRank);
        return true;
    }

    @Override
    public RankSingleGetOutput singleGet(Long id) {
        Optional<UnitRank> optionUnitRank = unitRankRepository.findById(id);
        if(!optionUnitRank.isPresent()){
            throw exception(UNIT_RANK_NOT_EXIST);
        }
        return RankConvert.INSTANCE.singleGetOutputConvert(optionUnitRank.get());

    }

    @Override
    public List<RankSimpleListOutput> simpleList() {
        return RankConvert.INSTANCE.simpleListOutputConvert(unitRankRepository.findAll());
    }

}
